package com.example.transaction.interceptor;

import com.alibaba.fastjson2.JSON;
import com.example.transaction.common.utils.JwtUtil;
import com.example.transaction.common.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
//JWt拦截器
public class JwtValidateInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token=request.getHeader("token");
        log.debug(request.getRequestURI()+"需要验证"+token);
        if(token!=null){
            try {
                jwtUtil.parseToken(token);
                log.debug(request.getRequestURI()+"通过");
                return true;
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        log.debug(request.getRequestURI()+"验证失败，禁止访问");
        response.setContentType("application/json;charset=utf-8");
        Result<Object>fail=Result.fail(20003,"jwt无效，请重新登录");
        response.getWriter().write(JSON.toJSONString(fail));
        return false;//拦截
//        // 获取所有的cookie
//        Cookie[] cookies = request.getCookies();
//        String token = null;
//
//        // 遍历cookie，找到名为"token"的cookie
//        if (cookies != null) {
//            for (Cookie cookie : cookies) {
//                if (cookie.getName().equals("token")) {
//                    token = cookie.getValue();
//                    break;
//                }
//            }
//        }
//
//        log.debug(request.getRequestURI() + "需要验证" + token);
//        if (token != null) {
//            try {
//                jwtUtil.parseToken(token);
//                log.debug(request.getRequestURI() + "通过");
//                return true;
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//
//        log.debug(request.getRequestURI() + "验证失败，禁止访问");
//        response.setContentType("application/json;charset=utf-8");
//        Result<Object> fail = Result.fail(20003, "jwt无效，请重新登录");
//        response.getWriter().write(JSON.toJSONString(fail));
//        return false; // 拦截
    }
}
